package com.bosssoft.hr.train.spring.example.service.impl;


import com.bosssoft.hr.train.spring.example.bean.User;
import com.bosssoft.hr.train.spring.example.dao.impl.UserDaoImp;
import com.bosssoft.hr.train.spring.example.service.UserCacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;

import java.util.List;

/**
 * @description 用户业务类 具备缓存功能，主要为了展示bean的装配以及spring cache的使用这里未作异常处理
 * @author ChenTong
 * @date 2020/6/5
 */
@Slf4j
public class UserCacheServiceImpl implements UserCacheService {

    private UserDaoImp userDao;

    //通过constructor方式注入
    public UserCacheServiceImpl(UserDaoImp userDaoImp) {
        this.userDao = userDaoImp;
    }

    public UserCacheServiceImpl(){

    }

    /**
     * 通过用户姓名进行查询并存放到userCache中 缓存区域为userCache
     * @param username:String 需要查询的用户名
     * @return User 查询到的用户
     */
    @Cacheable(value = "userCache")
    @Override
    public User queryUserByName(String username) {
        return this.userDao.queryUserByName(username);
    }

    /**
     * 查找所有用户并将结果存放到缓存中，缓存区域为userCache
     * @return List<User> 用户列表
     */
    @Cacheable(value = "userCache")
    @Override
    public List<User> queryAll() {
        return this.userDao.query();
    }

    /**
     * 通过用户姓名查询用户，并将其放入到缓存中，缓存区为usrCache
     * @param name:String 用户姓名
     * @return
     */
    @CachePut(value = "userCache")
    public User queryUserByNamePutCache(String name){
        return  this.userDao.queryUserByName(name);
    }

    /**
     * 清空缓存区 所清空的缓存区为userCache
     */
    @CacheEvict(value = "userCache",allEntries = true)
    public void cleanAllCache(){
        log.info("cache is clean");
    }

    public void init(){
        log.info("UserCacheService init()");
    }

    public void destroy(){
        log.info("UserCacheService destroy");
    }
}
